<template>
  <div class="search">
    <div>
      <ul class="search-type">
        <li @click="changeSearchType(item)" v-for="item in searchTypes" :key="item.type"
            :class="{'active': searchType === item.type}">{{ item.title }}
        </li>
      </ul>
      <!--@input="onInputSearch"-->
      <div class="search-main">
        <input class="search-input"
               @keyup.stop="onKeyup"
               @focus="onInputFocus"
               @click.stop="onInputClick"
               v-model.trim="keyword"
               :placeholder="searchTypes[searchType].placeholder"/>
        <button @click="search()" class="search-btn">搜 索</button>

        <div class="results" v-show="isShowSearch">
          <div class="search-result" v-show="searchList.length > 0">
            <ul>
              <li @mouseenter="mouseenter(index)" v-for="(item, index) in searchList" :key="item.keyword">
                <nuxt-link target="_blank"
                           :to="{path: searchType === 0 ? '/search':'enterprise', query:{ q: item.keyword}}"
                           :class="{'active': currentSelectIndex === index}">{{ item.keyword }}
                </nuxt-link>
              </li>
            </ul>
          </div>
          <div class="search-history" v-show="searchList.length <= 0 && historys.length > 0">
            <p class="search-tip">最近搜索</p>

            <div>
              <nuxt-link :to="{path: searchType === 0 ? '/search':'enterprise', query:{ q: item}}"
                         class="tag text-overflow"
                         target="_blank"
                         v-for="item in historys"
                         :key="item">{{item}}
              </nuxt-link>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="hot-search">
      <p v-if="hots.length > 0">
        <span>热门搜索：</span>

        <span v-for="item in hots" class="text-overflow">
          <nuxt-link v-if="!item.url"
                     target="_blank"
                     :title="item.hotWork"
                     :to="{path: '/search', query:{q: item.hotWork}}"
                     :key="item.hotWork">{{ item.hotWork }}
          </nuxt-link>

          <a v-else target="_blank" :href="item.url" :title="item.hotWork">{{ item.hotWork }}</a>
        </span>


      </p>
    </div>
    <MiniSearch @changeMiniSearch="changeMiniSearch" :searchTypes="searchTypes"></MiniSearch>
  </div>
</template>

<script>
  import axios from '~/plugins/axios'
  import MiniSearch from '~/components/MiniSearch'

  export default {
    props: {
      hot: {
        type: Array,
        'default': []
      }
    },
    components: {
      MiniSearch
    },
    data () {
      const type = this.$route.name === 'enterprise' ? 1 : 0
      return {
        timer: null,

        // 判断keyword 是否是第一次 解决当在一个有搜索关键字的url上取出回填到搜索框中的时候触发搜索
        keyword: this.$route.query.q,
        currentSelectIndex: 0,
        searchTypes: [
          {title: '商品', type: 0, placeholder: '请输入您要查询的商品名称'},
          {title: '企业', type: 1, placeholder: '请输入您要查询的企业名称'}
        ],

        hots: [],

        preveModel: this.$route.query.q,

        historys: [],

        searchList: [],

        isShowSearch: false,

        searchType: type
      }
    },

    watch: {
      async keyword (val, newVal) {

      },

      // 路由切换获取url 上的q 填充
      $route () {
        const query = this.$route.query
        this.keyword = query.q
        this.preveModel = this.keyword
      }
    },

    mounted () {
      // 填充搜索关键字
      const query = this.$route.query
      this.keyword = query.q
      this.prevKeyword = query.q

      // 从localStorage 中获取
      try {
        this.historysProducts = JSON.parse(localStorage.getItem('historysProducts')) || []
        this.historysEnterprises = JSON.parse(localStorage.getItem('historysEnterprises')) || []
      } catch (e) {
        console.log('历史搜索：' + e)
      }

      // 热门搜索
      this.getHot()

      // 绑定document 点击事件 隐藏搜索列表
      document.addEventListener('click', this.docuemtClick, false)
    },

    /**
     * 组件销毁的时候移除这个绑定的事件
     */
    destory () {
      document.removeEventListener('click', this.docuemtClick, false)
    },

    methods: {
      search () {
        let searchType = this.searchType === 0 ? 'search' : 'enterprise';
        this.$emit('searchSelect', {data: {keyword: this.keyword}, type: this.searchType})
        if (this.$route.name != searchType) {
          let q = this.keyword == '' || !this.keyword ? '' : '?q=' + this.keyword
          window.open('/' + searchType + q)
        } else {
          this.$router.push({
            path: searchType,
            query: {q: this.keyword}
          })
        }
      },
      /**
       * Mini搜索回调
       */
      changeMiniSearch (obj) {
        this.keyword = obj.keyword
        this.searchType = obj.searchType
        this.search()
      },
      submit (e) {
        e.preventDefault()
        return false
      },

      /**
       * 获取热门搜索关键字
       */
      async getHot () {
        const {hotWordList: hots = []} = await axios.get('/search/init').then(data => data.data.data)
        this.hots = hots
      },

      /**
       * document 点击
       * 重置选择索引、搜索列表
       */
      docuemtClick () {
        this.currentSelectIndex = 0
        this.isShowSearch = false
        this.searchList.length = 0
      },

      /**
       * input 光标获取事件
       */
      onInputFocus () {
        this.isShowSearch = true
        // 从localStorage 中获取
        try {
          this.historysProducts = JSON.parse(localStorage.getItem('historysProducts')) || []
          this.historysEnterprises = JSON.parse(localStorage.getItem('historysEnterprises')) || []
        } catch (e) {
          console.log('历史搜索：' + e)
        }

        if (this.searchType === 0) {
          this.historys = this.historysProducts
        } else {
          this.historys = this.historysEnterprises
        }
      },

      /**
       * input 点击
       */
      onInputClick () {
      },

      /**
       * 鼠标移入事件
       */
      mouseenter (index) {
        this.currentSelectIndex = index
      },

      /**
       * 隐藏下拉搜索列表框
       * 同时删除上一次的搜索列表
       */
      closeSearchList () {
        this.isShowSearch = false
        this.searchList = []
      },

      /**
       * 键盘事件
       */
      onKeyup (event) {
        clearTimeout(this.timer)

        this.timer = setTimeout(() => {
          const keyCode = event.keyCode
          // 判断输入的关键字 和 上一次输入的是否一样
          if (this.keyword !== this.preveModel) {
            // 数据重新查询 索引重置
            this.currentSelectIndex = -1

            // 数据请求
            axios.get('/search/suggestion_word', {
              params: {
                keyword: this.keyword,
                keywordType: this.searchType
              }
            }).then(data => {
              this.searchList = data.data.data || []
            })

            this.isShowSearch = true
          } else {
            switch (keyCode) {
              // ↑
              case 38:
                this.currentSelectIndex--
                if (this.currentSelectIndex < 0) {
                  this.currentSelectIndex = this.searchList.length - 1
                }

                // 填充input输入框
                // 填充input输入框
                if (this.searchList[this.currentSelectIndex]) {
                  this.keyword = this.searchList[this.currentSelectIndex].keyword
                }
                break

              // ↓
              case 40:
                this.currentSelectIndex++
                if (this.currentSelectIndex >= this.searchList.length) {
                  this.currentSelectIndex = 0
                }

                // 填充input输入框
                if (this.searchList[this.currentSelectIndex]) {
                  this.keyword = this.searchList[this.currentSelectIndex].keyword
                }

                break

              // Enter  执行父级的方法
              case 13:
                // 填充input输入框
                if (this.searchList[this.currentSelectIndex]) {
                  this.keyword = this.searchList[this.currentSelectIndex].keyword
                  this.$emit('searchSelect', {data: this.searchList[this.currentSelectIndex], type: this.searchType})
                } else {
                  this.$emit('searchSelect', {data: {keyword: this.keyword}, type: this.searchType})
                }

                this.closeSearchList()
                this.$router.push({
                  path: this.searchType === 0 ? '/search' : 'enterprise',
                  query: {q: this.keyword}
                })
                break
            }
          }
          this.preveModel = this.keyword
        }, 60)
      },

      /**
       * 改变搜索类型
       * @param item
       */
      changeSearchType (item) {
        this.searchType = item.type
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import "../element-variables";

  .tag {
    padding: 6px 14px;
    text-align: center;
    border: 1px solid #dedede;
    color: #6e6e6e;
    margin-right: 10px;
    display: inline-block;
    border-radius: 2px;
    max-width: 100px;
    background-color: #fff;
  }

  .hot-search {
    color: #9e9e9e;
    padding-top: 3px;
    padding-left: 14px;
    height: 20px;

    span {
      float: left;
      max-width: 100px;
      margin-right: 15px;
    }

    a:hover {
      color: $--color-primary;
    }
  }

  .search {
    width: 100%;
    font-size: 12px;

    .search-main {
      background-color: $--color-primary;
      padding: 2px 0 2px 2px;
      height: 36px;
      position: relative;
    }

    .results {
      position: absolute;
      top: 100%;
      left: 0;
      width: 85%;
      background: #fff;
      border: 1px solid #dedede;
      border-top: none;
      border-radius: 2px;
      z-index: 21;
      /*display: none;*/
    }

    .search-result {
      a {
        display: block;
        line-height: 32px;
        padding-left: 10px;
        color: #3e3e3e;
        font-size: 14px;

        &:hover, &.active {
          background-color: #f5f5f5;
        }
      }
    }

    .search-history {
      padding: 10px;
      color: #9e9e9e;
      .tag {
        margin-top: 10px;

        &:hover {
          color: #fff;
          background-color: rgba($--color-primary, .8);
          border-color: $--color-primary;
        }
      }

      .search-tip {
        margin: 0;
      }
    }

    .search-input {
      width: 100%;
      border: none;
      height: 100%;
      padding: 0 90px 0 12px;

      &:focus {
        outline: none;
      }
    }
    .search-btn {
      background-color: $--color-primary;
      color: #fff;
      border: none;
      height: 100%;
      width: 80px;
      line-height: 36px;
      text-align: center;
      font-size: 16px;
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
    }

    .search-type {
      height: 28px;

      li {
        float: left;
        line-height: 28px;
        color: #3e3e3e;
        padding: 0 15px;
        cursor: pointer;
      }

      .active {
        background-color: #b78730;//$--color-primary;
        color: #fff;
      }
    }
  }
</style>
